package configfactory;

import entity.AmeiracaCoffee;
import entity.NaTieCoffee;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SimpleFactory {
    //用来存放工厂创建的对象
    static  Map<String,Object> map=new HashMap<>();

    static {
        //1.读取xml文件
        //1.创建解析器
        SAXReader reader=new SAXReader();
        //2.读取xml得到document对象
        try {
            Document document = reader.read("ch03/src/bean.xml");
            //3.读取根节点
            Element rootElement = document.getRootElement();
            //4.读取二级节点
            List<Element> list = rootElement.elements("bean");
            //5.遍历
            for (Element element : list) {
                String className=element.attributeValue("class");
                //获取Class
                Class clz=Class.forName(className);
                //创建对象
                Object obj=clz.newInstance();

                String id=element.attributeValue("id");
                map.put(id,obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Object getBean(String id){
        return map.get(id);
    }
}
